package com.jiehoo.elove.robot;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import rath.msnm.msg.MimeMessage;
import rath.msnm.msg.OutgoingMessage;

public class RobotServer extends Thread {
	private static Log log = LogFactory.getLog(RobotServer.class);

	private static final String CONFIGURE_FILE = "elove.properties";

	private static Configuration systemConfiguration;

	private static List<Robot> robots = new ArrayList<Robot>();

	private static RobotServer instance = new RobotServer();

	public static MimeMessage noOtherUser;

	public static MimeMessage typing;

	public static OutgoingMessage exit = new OutgoingMessage("OUT");

	public static int timeout;

	public static void main(String[] args) {
		try {
			systemConfiguration = new PropertiesConfiguration(CONFIGURE_FILE);
			initServerParameter();
			File configureDirectory = new File(systemConfiguration
					.getString("robots.configuration.dir"));
			if (!configureDirectory.exists()) {
				log.error(configureDirectory.getAbsolutePath()
						+ " does not exist!");
				return;
			}
			if (!configureDirectory.isDirectory()) {
				log.error(configureDirectory.getAbsolutePath()
						+ " is not a directory!");
				return;
			}
			File[] configures = configureDirectory
					.listFiles(new FileNameFilter(systemConfiguration
							.getString("robots.configuration.name_pattern")));
			if (configures.length == 0) {
				log.error("There is no any configure file!");
				return;
			}
			for (int i = 0; i < configures.length; i++) {
				Configuration configuration = new PropertiesConfiguration(
						configures[i]);
				Robot robot = new Robot(configuration);
				robots.add(robot);
				robot.login();
			}
			Runtime.getRuntime().addShutdownHook(instance);
		} catch (ConfigurationException e) {
			log.error("Can not start robot server",e);
		}
	}

	protected static void initServerParameter() {
		noOtherUser = new MimeMessage(systemConfiguration
				.getString("system.noOthers.message"));
		noOtherUser.setKind(MimeMessage.KIND_MESSAGE);
		typing = new MimeMessage(systemConfiguration
				.getString("system.typing.message"));
		typing.setKind(MimeMessage.KIND_MESSAGE);
		timeout = systemConfiguration.getInt("system.session.timeout");
	}

	public void run() {
		for (int i = 0; i < robots.size(); i++) {
			Robot robot = (Robot) robots.get(i);
			robot.logout();
		}
	}
}